﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace CC98.Data
{
    public class UserManager
    {
        private static readonly object _syncRoot = new object();
        private static volatile UserManager _instance;

        public static UserManager Instance
        {
            get
            {
                if (_instance == null)
                    lock (_syncRoot)
                        if (_instance == null)
                            _instance = new UserManager();
                return _instance;
            }
        }

        private UserManager() { }

        public User GetUser(string name)
        {
            return new User(name);
        }

        public async Task LoadUsersAsync()
        {
            var file = await ApplicationData.Current.LocalFolder.GetFileAsync("Users.bin");
            using(var stream = await file.OpenStreamForReadAsync())
            {
                var users = SerializeHelper.DeserializeJson<User[]>(stream);
                foreach (var user in users)
                    this._userDict[user.Name] = user;
            }
        }

        public async Task SaveUsersAsync()
        {
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Users.bin", CreationCollisionOption.ReplaceExisting);
            using (var stream = await file.OpenStreamForReadAsync())
            {
                var users = this._userDict.Values.ToArray();
                SerializeHelper.SerializeJson<User[]>(users, stream);
            }
        }

        private readonly Dictionary<string, User> _userDict = new Dictionary<string, User>();
    }
}
